from django.views import View
from django.http import JsonResponse, HttpResponse
from django.conf import settings
from django.shortcuts import redirect

from backend.libs.upyun import up
from backend.utils.nowTime import nowtime


class UploadEditorImg(View):

    def post(self, request):

        file = request.FILES.get('upload')

        img_name = nowtime + file.name

        try:
            up.put(f'/tensquare/img/{img_name}', file.read())
        except Exception as e:
            return JsonResponse({
                'message': '上传失败',
            }, status=400)

        return redirect(settings.UPYUN_BASE_URL + img_name)


class UploadAvatar(View):

    def post(self, request):

        file = request.FILES.get('img')

        img_name = nowtime + file.name

        try:
            up.put(f'/tensquare/img/{img_name}', file.read())
        except Exception as e:
            return JsonResponse({
                'message': '上传失败',
            }, status=400)

        return JsonResponse({'imgurl': settings.UPYUN_BASE_URL + img_name})



